package com.anxin.act.model.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anxin.act.config.entity.WfApplyForm;
import com.anxin.act.config.entity.WfApplyFormField;
import com.anxin.act.config.service.WfApplyFormService;
import com.anxin.act.model.dto.ActModelExportDTO;
import com.anxin.act.model.service.ActModelService;
import com.anxin.act.model.vo.ActModelVo;
import com.anxin.act.utils.ActUtils;
import com.anxin.common.utils.LogUtils;
import com.anxin.framework.aspectj.lang.annotation.Log;
import com.anxin.framework.aspectj.lang.enums.BusinessType;
import com.anxin.framework.security.service.TokenService;
import com.anxin.framework.web.controller.BaseController;
import com.anxin.framework.web.entity.AjaxResult;
import com.anxin.framework.web.page.TableDataInfo;
import org.activiti.engine.repository.Model;
import org.apache.poi.hssf.record.SaveRecalcRecord;
//import org.elasticsearch.http.netty4.pipelining.HttpPipelinedRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 工作流模型模型
 *
 * @author : liuxiangyu
 * @date: 2020/3/4 17:39
 */
@RestController
@RequestMapping("/act/model")
public class ActModelController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger("sys-error");

    @Autowired
    private ActModelService actModelService;

    @Autowired
    private WfApplyFormService wfApplyFormService;


    /**
     * 根据ID获取模型信息
     */
    @PreAuthorize("@ss.hasPermi('act:model:view')")
    @GetMapping(value = "/{id}")
    @Log(title = "根据ID获取模型信息", businessType = BusinessType.LIST)
    public AjaxResult getInfo(@PathVariable("id") String id){
        return AjaxResult.success(actModelService.get(id));
    }

    /**
     * 查询模型列表
     * @param actModelVo 查询参数
     * @return
     */
    @PreAuthorize("@ss.hasPermi('act:model:view')")
    @GetMapping("/list")
    @Log(title = "查询模型列表", businessType = BusinessType.LIST)
    public TableDataInfo list(ActModelVo actModelVo){
        return actModelService.findList(actModelVo);
    }

    /**
     * 保存模型
     */
    @PreAuthorize("@ss.hasPermi('act:model:edit')")
    @Log(title = "流程模型", businessType = BusinessType.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody ActModelVo actModelVo) throws UnsupportedEncodingException {
        return actModelService.saveModel(actModelVo);
    }

    /**
     * 删除模型
     */
    @PreAuthorize("@ss.hasPermi('act:model:remove')")
    @Log(title = "流程模型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable(("id")) String id){
        return actModelService.delete(id);
    }

    /**
     * 部署流程
     * @param id 模型ID
     * @return
     */
    @PreAuthorize("@ss.hasPermi('act:model:edit')")
    @Log(title = "流程模型", businessType = BusinessType.DEPLOY)
    @PostMapping("/deploy/{id}")
    public AjaxResult deploy(@PathVariable(("id")) String id) throws Exception {
        try {
            actModelService.deploy(id);
        }catch (Exception e){
            logger.error("部署流程异常", e);
            return AjaxResult.error("流程部署异常,请检查流程配置或联系系统管理员,错误原因:"+e.getMessage());
        }
        return AjaxResult.success();
    }


    /**
     * 根据流程定义的key获取表单信息
     * @param procDefKey
     * @return
     */
    @GetMapping(value = "/getFormInfo/{procDefKey}")
    @Log(title = "根据流程定义的key获取表单信息", businessType = BusinessType.LIST)
    public AjaxResult getFormInfo(@PathVariable("procDefKey") String procDefKey){
        return AjaxResult.success(ActUtils.getActFormPathByProcDefKey(procDefKey));
    }

    /**
     * 校验流程标识是否重复
     * @param actModelVo
     * @return
     */
    @GetMapping("/checkKey")
    @Log(title = "校验流程标识是否重复", businessType = BusinessType.LIST)
    public AjaxResult checkKey(ActModelVo actModelVo){
        return AjaxResult.success(actModelService.checkKey(actModelVo));
    }

    /**
     * 模型导出
     * @param actModelExportDTO 导出模型
     * @return
     */
    @PostMapping("/export")
    @Log(title = "模型导出", businessType = BusinessType.EXPORT)
    public void export(@RequestBody ActModelExportDTO actModelExportDTO, HttpServletRequest request, HttpServletResponse response){
        try {
            actModelService.export(actModelExportDTO,request,response);
        }catch (Exception e){
            LogUtils.error("流程导出失败,详情请查看日志",e);
        }
    }

    /**
     * 模型导入
     * @param file 导入文件
     * @return
     */
    @PostMapping("/importData")
    @Log(title = "模型导入", businessType = BusinessType.IMPORT)
    public AjaxResult importData(MultipartFile file){
        try {
            actModelService.importData(file);
        }catch (Exception e){
            return AjaxResult.error("流程导出失败,详情请查看日志");
        }
        return AjaxResult.success();
    }

    /**
     * 根据原型ID获取对应的表单字段
     * @return
     */
    @GetMapping(value = "/getFormField/{modelId}")
    @Log(title = "根据原型ID获取对应的表单字段", businessType = BusinessType.LIST)
    public AjaxResult getFormField(@PathVariable("modelId") String modelId, HttpServletRequest request){

        // TODO 待优化
        ActModelVo actModelVo = actModelService.get(modelId);
        if ("dev".equals(actModelVo.getFormType())){
            WfApplyForm wfApplyForm = wfApplyFormService.getById(actModelVo.getFormId());
            List<WfApplyFormField> wfApplyFormFieldList = wfApplyForm.getWfApplyFormFieldList();
            JSONArray fieldArray = new JSONArray();
            for (WfApplyFormField wfApplyFormField : wfApplyFormFieldList) {
                JSONObject filedJson = new JSONObject();
                filedJson.put("id",wfApplyFormField.getId());
                filedJson.put("name",wfApplyFormField.getRemark()+"("+wfApplyFormField.getName()+")");
                filedJson.put("value",wfApplyFormField.getName());
                filedJson.put("type",wfApplyFormField.getType());
                filedJson.put("dictType",wfApplyFormField.getDictType());
                fieldArray.add(filedJson);
            }
            return AjaxResult.success(fieldArray);
        }

        return AjaxResult.error("为查询到数据");
    }
}
